﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.OAuthLogin;
using Microsoft.AspNetCore.OAuthLogin.Config;
using Microsoft.AspNetCore.OAuthLogin.Model;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

namespace Microsoft.AspNetCore.OAuthLogin
{
    /// <summary>
    /// qq登陆
    /// </summary>
    public class QQ : BaseLogin
    {
        private OAuthCredentials _credentials;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContextAccessor"></param>
        /// <param name="options"></param>
        public QQ(IHttpContextAccessor httpContextAccessor, IOptions<OAuthCredentials> options)
            : base(httpContextAccessor)
        {
            this._credentials = options.Value;
        }

        private string authorize_url { get; set; }

        /// <summary>
        /// 跳转的地址
        /// </summary>
        public override string Authorize_Url => authorize_url;

        /// <summary>
        /// 登陆验证
        /// </summary>
        /// <returns></returns>
        public OAuthResult Authorize()
        {
            OAuthResult result = new OAuthResult();
            authorize_url = $"https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id={_credentials.QQ.client_id}&redirect_uri={CallbackUrl}";

            if (String.IsNullOrEmpty(AuthorizeCode))
            {
                return null;
            }
            var dic = Accesstoken(AuthorizeCode);
            if (dic != null)
            {
                result.User = UserInfo(dic["access_token"]);
                if (result.User.Value<int>("ret")==0)
                {
                    result.code = 0;
                    result.User = result.User;
                }
                else
                {
                    result.errormsg = result.User.Value<string>("msg");
                    result.code = 2;
                }
            }
            else
            {
                result.errormsg = "QQ获取token出错";
                result.code = 1;
            }
            return result;
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private Dictionary<string, string> Accesstoken(string code)
        {
            string oauth_url = $"https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id={_credentials.QQ.client_id}&client_secret={_credentials.QQ.client_secret}&code={code}&redirect_uri={CallbackUrl}";
            var data = new SortedDictionary<string, string>();
            using (var httpClient = new HttpClient())
            {
                var response = httpClient.GetAsync(oauth_url).Result;
                var result = response.Content.ReadAsStringAsync().Result;
                var kvs = result.Split(new string[] { "&" }, StringSplitOptions.RemoveEmptyEntries);

                var dic = new Dictionary<string, string>();

                foreach (var v in kvs)
                {
                    var kv = v.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);

                    dic.Add(kv[0], kv[1]);
                }
                return dic;
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        private JObject UserInfo(string token)
        {
            string openid_url = $"https://graph.qq.com/oauth2.0/me?access_token={token}";
            using (var httpClien = new HttpClient())
            {
                var response = httpClien.GetAsync(openid_url).Result;

                var result = response.Content.ReadAsStringAsync().Result;

                result = result.Replace("callback(", string.Empty).Replace(");", string.Empty).Trim();

                var openid = JsonConvert.DeserializeObject<JObject>(result).Value<string>("openid");
                string user_info_url = $"https://graph.qq.com/user/get_user_info?access_token={token}&oauth_consumer_key={_credentials.QQ.client_id}&openid={openid}";
                var userResponse = httpClien.GetAsync(user_info_url).Result;
                var userSring = userResponse.Content.ReadAsStringAsync().Result;

                return JsonConvert.DeserializeObject<JObject>(userSring);
            }
        }



    }
}
